import { regGoodsInfo } from '../../../api/goods'
import { userBehavior } from '../../../behaviors/userBehavior'
import { reqAddCart, reqCartList } from '../../../../../api/cart'
import { toast } from '../../../../../utils/expendApi'
Page({
  behaviors: [userBehavior],
  /**
   * 页面的初始数据
   */
  data: {
    goodsInfo: {}, // 商品详情
    show: false, // 控制加入购物车和立即购买弹框的显示
    count: 1, // 商品购买数量，默认是 1
    blessing: '', // 祝福语
    buyNow: 0, // 控制加入购物车还是立即购买
    allCount: '', //商品的购买数量
  },
  // 获取详情
  async getGoodsInfo () {
    const { data:goodsInfo } = await regGoodsInfo(this.goodsId)
    this.setData({ goodsInfo})
  },
  // 计算购物车商品数量
  async getCartCount () {
    // 判断是否登录
    if(!this.data.token) return 
    const res = await reqCartList()
    if(res.data.length !== 0) {
      let allCount = 0
      res.data.forEach(item => {
        allCount += item.count
      })
      // info属性的要求是 字符串类型 如果大于99需要展示99+
      this.setData({
        allCount: allCount>99?'99+': (allCount+'')
      })
    }
  },
  // 加入购物车
  handleAddcart() {
    this.setData({
      show: true,
      buyNow: 0
    })
  },

  // 立即购买
  handeGotoBuy() {
    console.log('立即购买 gotobuy')
    this.setData({
      show: true,
      buyNow: 1
    })
  },
  // 点击关闭弹框时触发的回调
  onClose() {
    this.setData({ show: false })
  },

  // 预览
  previewImage () {
    console.log(this.data.goodsInfo.detailList)
    wx.previewImage({
      urls: this.data.goodsInfo.detailList,
    })
  },
  // 监听是否更改了购买数量
  onChangeGoodsCount(event) {
    // console.log(event.detail)
    this.setData({
      count:  Number(event.detail)
    })
  },
  // 弹框确定按钮触发的事件处理函数
  async handlerSubmit () {
    const { token, count, blessing, buyNow } = this.data
    const goodsId = this.goodsId
    if(!token) {
      wx.navigateTo({
        url: '/pages/login/login',
      })
      return
    }
    if(buyNow === 0) {
      // 加入购物车
      const res = await reqAddCart({ goodsId, count, blessing})
      if(res.code === 200) {
        toast({title: '加入购物车成功~'})
        // 重新计算购物车数量
        this.getCartCount()
        // 关闭弹窗
        this.setData({
          show: false
        })
      } 
    }else {
      // 立即购买
    wx.navigateTo({
      url: `/modules/orderPayModule/pages/order/detail/detail?goodsId=${goodsId}&blessing=${blessing}`,
    })
    }
  },
  onLoad(options) {
    this.goodsId = options.goodsId
    this.getGoodsInfo()
    this.getCartCount()
  },
})